/**
* jTabs - Tabs Manager for jQuery  
* Released under GPL v3 License
* @author Cristian Ariel Cortez  
* @copyright (c) 2010 - 2012 Cristian Ariel Cortez - cortez[dot]cristian[at]gmail[dot]com - http://skyconcept.com.ar/crisboot/
* @date 25/01/2011
* @requires jQuery v1.4 or above
*
*/

/**
*  HTML markup example:
* <div class="tabs">
*	<div class="tab-ctrl tab-ctrl-left"><a href="#">&nbsp;</a></div>
*	<div class="tab-ctrl tab-ctrl-right"><a href="#">&nbsp;</a></div>
*	<div class="tabs-show">
*		<ul class="tabs-list">
*			<li>
*				<span>
*					<a href="#panel1" class="tab-tittle">Panel 1</a>
*					<a href="#panel1" class="tab-close"></a>
*				</span>
*				<span class="tab-end"></span>
*			</li>
*			<li>
*				<span>
*					<a href="#panel2" class="tab-tittle">Panel 2</a>
*					<a href="#panel2" class="tab-close"></a>
*				</span>
*				<span class="tab-end"></span>
*			</li>
*		</ul>
*	</div>
*	<div class="tabs-panels">
*		<div id="panel1" class="tab-panel-content">
*			<h2>Panel 1 Content</h2>
*			<p>Este es el primer contenido</p>
*		</div>
*		<div id="panel2" class="tab-panel-content">
*			Panel 2 Content
*		</div>
*	</div>
* </div>
*
*/

;(function($){
	$.fn.jtabs = function(obj){
		/**
		* Configuration Object
		*/
		var o = $.extend({			
			afterEnd: function(instObject){ 
				//by default call the first tab
				instObject.find('.tabs-list li:first-child a.tab-tittle').click();
				
				if(o.accessibilityEnabled)
					o.handleAccessibility(instObject);
			},
			onClose: function(id, content){
				//handler to hold the id and the content of the closed tab
				debuger("A tab have been closed");
				debuger("id:" + id);
				debuger("content:" + content);
			},
			onResize: function(instObject){
				debuger("resize");
				// debuger(instObject);
				// debuger(instObject.parent());
				//debuger(instObject.parent().width());
				// instObject.parent().width(instObject.parent().parent().width());
				// instObject.width(instObject.parent().width());
				// instObject.find('.tabs-show').width(instObject.find('.tabs-show').parent().width());
			},
			onSelect: function(id){
				debuger("A tab have been selected:"+id)
			},
			handleAccessibility: function(instObject){
				debuger("Accessibility to the rescue");
				if($('.tabs-with-accessibility').size()==1){
					var isCtrl = false, isAlt=false;
					$(document).keyup(function (e) {
						if(e.which == 17) isCtrl=false;
						if(e.which == 18) isAlt=false;
					}).keydown(function (e) {
						if(e.which == 17) isCtrl=true;
						if(e.which == 18) isAlt=true;
						
						if(e.which == 33 && isCtrl == true && isAlt == true) {//33- page up
							debuger("control + Alt + Page Up");
							if(instObject.find('li.actual').next().size()>0)
								instObject.find('li.actual').next().find('.tab-tittle').click();
							
							return false;
						}
						
						if(e.which == 34 && isCtrl == true && isAlt == true) {//34- page down
							debuger("control + Alt + Page Down");
							
							if(instObject.find('li.actual').prev().size()>0)
								instObject.find('li.actual').prev().find('.tab-tittle').click();
							
							return false;
						}
						
						if(e.which == 81 && isCtrl == true && isAlt == true) {//81- q
							debuger("Close current tab");
							
							instObject.find('li.actual').find('.tab-tittle').next().click();
							
							return false;
						}
						
					});
				}//if ends	
				
			},
			accessibilityEnabled: false,
			animatePixels: 'auto',
			closable: true,
			debug: true,
			debugColors: false,
			minTabSize: 120,
			maxTabSIze: 160
		}, obj || {});
		
		/**
		* Function Debuger to show logs in Firebug
		*/
		function debuger(){
			if(o.debug)
				try{console.log.apply('',arguments);} catch(e) {}
			//$('.p-south .panel-content .code').css('overflow','scroll').append('<p>'+arguments[0]+'</p>').attr('scrollTop',$('.p-south .panel-content .code').attr('scrollHeight'));
		}
		
		return this.each(function() {
			//console.log($(this));
			debuger(location.hash);
		
		var curIns = $(this), //current Instance
		cMove = (o.animatePixels=='auto') ? $('ul.tabs-list li').eq(0).width() : o.animatePixels;	//amount of pixels to animate
		
		if($(curIns,location.hash).size()){
			//curIns.find(location.hash
			//curIns.find('.tabs-list li a.tab-tittle'){
				
			//}
			location.hash = "";
			debuger("Lo encuentra");
		}
		
		//hide all panels
		curIns.find('.tab-panel-content').hide();
		
		/**
		* Function getTlWidth for obtaining the witdh of the list f tabs
		*/
		function getTlWidth(instObject){
			var tlWidth = 0;
			instObject.find('ul.tabs-list li').each(function(index, value){
				tlWidth += $(this).width() + parseInt($(this).css('margin-left'))*2;
			});
			return tlWidth;
		}
		/**
		* Function reaccomodateTab for showing the entire tab body
		*/
		function reaccomodateTab(tab){
			if(tab.offset().left+tab.parent().parent().width()>curIns.find('.tabs-show').width()){
				debuger('it is hidden to the rigth');
				curIns.find('.tab-ctrl-right a').click();
			}
			if(tab.offset().left<$('.tabs').offset().left+24){
				debuger('it is hidden to the left');
				curIns.find('.tab-ctrl-left a').click();
			}
		}
		//add class tabs-running
		curIns.addClass('tabs-running');
		// add accessibility detection class
		if(o.accessibilityEnabled)
			curIns.addClass('tabs-with-accessibility');
		
		//set tabs-list width
		curIns.find('ul.tabs-list').width(getTlWidth(curIns));
		//set tabs show width the same than the parent element
		curIns.find('.tabs-show').width(curIns.find('.tabs-show').parent().width());
		
		//show content
		curIns.find('.tabs-list li a.tab-tittle').live('click', function(e){
			e.preventDefault();
			var cur = $(this), idContent;
			curIns.find('.tabs-list li a.selected').removeClass('selected');
			cur.addClass('selected');
			curIns.find('.tabs-list li.actual').removeClass('actual');
			cur.parent().parent().addClass('actual');
			
			if(cur.attr('href')!='#' && cur.attr('hash').match(/^#/)){
				idContent = cur.attr('hash');
				//callback for onSelect
				o.onSelect(idContent);
				curIns.find('.tab-panel-content').hide();
				$(idContent).show();
				//tab data
				debuger("offset left: "+$(this).offset().left)
				debuger("width: "+($(this).offset().left+cur.parent().parent().width()))
				debuger("tabs-show width: "+curIns.find('.tabs-show').width())
				debuger("tabs width: "+curIns.offset().left)
				//we need to accomodate the data
				reaccomodateTab($(this))
				/* ///Replace with reaccomodateTab : function
				if($(this).offset().left+cur.parent().parent().width()>curIns.find('.tabs-show').width()){
					debuger('it is hidden to the rigth');
					curIns.find('.tab-ctrl-right a').click();
				}
				if($(this).offset().left<$('.tabs').offset().left+24){
					debuger('it is hidden to the left');
					curIns.find('.tab-ctrl-left a').click();
				}*/
			}
		});
		
		//close tab
		curIns.find('.tabs-list li a.tab-close').live('click', function(e){
			e.preventDefault();
			var cur = $(this), curP = $(this).parent(), idContent, clickEl, reacTab;
			if(cur.attr('href')!='#' && cur.attr('hash').match(/^#/)){
				idContent = cur.attr('hash');
				debuger(curIns.find('.tabs-list li').length + " | " +$(this).parent().index() +" | "+ curIns.find('.tabs-list li').length);
				debuger(curP.parent().index()!=0);
				debuger(curIns.find('.tabs-list li').length>1);
				debuger($(this).prev().hasClass('selected'));
				debuger(curP.parent().prev());
				debuger(curP.parent().next());
				debuger("(getTlWidth(curIns)): "+(getTlWidth(curIns)));
				debuger("tab show width: "+curIns.find('.tabs-show').width());
				debuger("curP.parent().index(): "+curP.parent().index());
				debuger("entra: "+(curP.parent().index()==curIns.find('.tabs-list li').length));
				if(curP.parent().index()!=0 && curIns.find('.tabs-list li').length>1 && $(this).prev().hasClass('selected')){
					/* When closing, make sure:
						1- The tab is not the first
						2- the number of tabas is at least 2
						3- And that this is the selected tab
					*/
					//hold the previous tab to select it later
					clickEl = curP.parent().prev();
				}else if(curP.parent().index()==0 && curIns.find('.tabs-list li').length>1 && $(this).prev().hasClass('selected')){
					/* When closing, make sure:
						1- The tab is the first
						2- the number of tabas is at least 2
						3- And that this is the selected tab
					*/
					//hold the next tab to select it later
					clickEl = curP.parent().next();
				}
				
				//if((curP.parent().index()+1)==curIns.find('.tabs-list li').length && (getTlWidth(curIns))>curIns.find('.tabs-show').width()){
				//2- The width of the list is still major than the width of the tab-show-mask-region
				if((curP.parent().index()+1)==curIns.find('.tabs-list li').length){
					/* When closing, make sure:
						1- The tab is the last
					*/
					debuger("I'm the last animate me!"+cMove);
					//curIns.find('.tabs-list').animate({'left': cMove}, 'fast');
					curIns.find('.tab-ctrl-left a').click();
				}
				
				//Sometimes we need to reacomodate the selected tab, cause we wanna make sure that the body tab is visible
				if(!$(this).prev().hasClass('selected')){//the closed tab is not the selected
					debuger("we need to reaccomodate the tab");
					reacTab = true;
				}
				
				//call the handler on Close
				o.onClose(idContent, $(idContent).html());
				//remove the content and the tab
				$(idContent).remove();
				curP.parent().remove();
				
				if(reacTab){//
					reaccomodateTab(curIns.find('.tab-tittle.selected'));
				}
				
				//set the new width for tl
				curIns.find('ul.tabs-list').width(getTlWidth(curIns));
				
				//if exists call the appropiate tab
				if(clickEl)
					clickEl.find('.tab-tittle').click();
			}
		});
		
		//move tabs left
		curIns.find('.tab-ctrl-left a').live('click', function(e){
			e.preventDefault();
			var left  = parseFloat(curIns.find('.tabs-list').css('left'))/*.replace(/px/,'');*/,arrowP =$(this).parent(),
			//qTabs = curIns.find('.tabs-list li').length, widthTab = curIns.find('.tabs-list li:first-child').width(),
			widthShow = curIns.find('.tabs-show').width(), z = curIns.find('.tabs-list').width()+40, limit = 0;
			
			if(z>=widthShow){//not working on IE6
				limit = (-1)*(widthShow*(widthShow/z));
				//limit = (-1)*(widthShow*(widthShow/z));
				//limit = (-1)*(widthShow-z);
			}
			
			debuger(left);
			debuger(left+20);
			if(left<0){
				var moveMe = (left+cMove>0)?0:(left+cMove);
				curIns.find('.tabs-list').animate({'left': moveMe}, 'fast');
				if(arrowP.hasClass('disabled'))
					arrowP.removeClass('disabled');
			}else{
				arrowP.addClass('disabled');
			}
				//curIns.find('.tabs-list').css('left', (left+20));
			debuger("2>"+curIns.find('.tabs-list').css('left'));
		});
		
		//move tabs right
		curIns.find('.tab-ctrl-right a').live('click', function(e){
			e.preventDefault();
			var left  = parseFloat(curIns.find('.tabs-list').css('left')), arrowP =$(this).parent(),
			widthShow = curIns.find('.tabs-show').width(), z = curIns.find('.tabs-list').width()+40, limit = 0;
			//alert('widthShow: '+widthShow+' z: '+z+' rel :'+(z>=widthShow));
			
			if(z>=widthShow){//not working on IE6
				//limit = (-1)*((widthShow*(widthShow/(z)))-curIns.find('.tabs-list li:last-child').width());
				//limit = (-1)*(widthShow*(widthShow/z));
				limit = (-1)*(z-widthShow);
				//limit = (-1)*(widthShow-(z-curIns.find('.tabs-list li:last-child').width()));
			}

			debuger(left);
			//alert('left: '+left+' limit; '+limit+' rel :'+(left<=0&&left>limit));
			if(left<=0&&left>limit){
				var moveMe = (left-cMove<limit)?limit:(left-cMove);
				debuger("moving: "+(left-cMove)+" | z: "+z+" | limit: "+limit+" | moveMe: "+moveMe);		
				curIns.find('.tabs-list').animate({'left': moveMe}, 'fast');
				//curIns.find('.tabs-list').css('left', (left-20));
				if(arrowP.hasClass('disabled'))
					arrowP.removeClass('disabled');
			}else{
				arrowP.addClass('disabled');
			}
			debuger("2>"+curIns.find('.tabs-list').css('left'));
		});
		
		$(window).resize(function() {
			//debuger(curIns)
			o.onResize(curIns);
				
		});
		
		o.afterEnd(curIns);
		});//close return
	}
})(jQuery);



